﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Rezene.Web.Business;
using Rezene.Web.Business.Amazon;
using Rezene.Web.Business.Amazon.Entities;

namespace Rezene.Web.Controllers
{
    public class BaseController : Controller
    {
        public IConfigurationRepository ConfigurationRepository { get; set; }
        public IAmazonRepository AmazonRepository { get; set; }

        public bool IsAuthorized
        {
            get
            {
                return User.Identity.IsAuthenticated;
            }
        }

        protected string CurrentGalleryPath()
        {
            var path = Request.Path;
            string cleanPath = string.Empty;
            if (path.Contains("/Gallery/List"))
            {
                cleanPath = GetCleanPath(path);
            }
            else if (!string.IsNullOrEmpty(Request.QueryString["path"]))
            {
                path = Request.QueryString["path"];
                int lastSlash = path.LastIndexOf("/");
                if (lastSlash > 0)
                {
                    cleanPath = GetCleanPath(path.Substring(0, lastSlash));
                }
                else
                {
                    cleanPath = GetCleanPath(path);
                }

            }
            return cleanPath;
        }

        protected S3Gallery GetCurrentGalery()
        {
            var cleanPath = CurrentGalleryPath();
            if (!string.IsNullOrEmpty(cleanPath))
            {
                var items = cleanPath.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
                if (items.Any())
                {
                    var amazonPath = cleanPath.Substring(0, cleanPath.IndexOf(items.Last()) + items.Last().Length);
                    return AmazonRepository.GetGalleryInfo(amazonPath);
                }
            }
            return null;
        }

        protected string GetCleanPath(string path)
        {
            var galleryPath = path.Replace("/Gallery/List/", "");
            return galleryPath.EndsWith("/") ? galleryPath.Substring(0, galleryPath.Length - 1) : galleryPath;
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!AmazonRepository.IsInitialized())
            {
                AmazonRepository.Init(
                    ConfigurationRepository.GetAmazonAccessKey(),
                    ConfigurationRepository.GetAmazonSecretKey(),
                    ConfigurationRepository.GetAmazonEndPoint(),
                    ConfigurationRepository.GetAmazonContainerBucket()
                    );
                AmazonRepository.AllowedExtensions = ConfigurationRepository.GetAllowedExtensions();
            }
        }     
    }
}